package utilities;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * This program reads a text file line by line and print to the console. It uses
 * FileOutputStream to read the file.
 * 
 */
public class FileInput {
	private String fileLocation;
	private File file;
	private FileInputStream fis;
	private BufferedInputStream bis;
	private DataInputStream dis;

	public FileInput(){

	}

	public String getFileLocation() {
		return fileLocation;
	}

	public void setFileLocation(String fileLocation) {
		this.fileLocation = fileLocation;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public FileInputStream getFis() {
		return fis;
	}

	public void setFis(FileInputStream fis) {
		this.fis = fis;
	}

	public BufferedInputStream getBis() {
		return bis;
	}

	public void setBis(BufferedInputStream bis) {
		this.bis = bis;
	}

	public DataInputStream getDis() {
		return dis;
	}

	public void setDis(DataInputStream dis) {
		this.dis = dis;
	}

	public FileInput(String fileAddress){
		this.fileLocation = fileAddress;
		file = new File(fileAddress);
		fis = null;
		bis = null;
		dis = null;
		setDataInputStream();
	}

	public void setDataInputStream(){
		try {
			fis = new FileInputStream(file);
			// Here BufferedInputStream is added for fast reading.
			bis = new BufferedInputStream(fis);
			dis = new DataInputStream(bis);
			System.out.println("file read completed: " + file.getName());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	public char next() {
		char c = ' ';
		try {
			c = (char) dis.read();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return c;
	}

	@SuppressWarnings("deprecation")
	public String nextLine() {
		String str = "";
		// this statement reads the line from the file and print it to
		// the console.
		try {
			str = dis.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str;
	}

	/**
	 * returns false if the file does not have more lines.
	 * @return next
	 */
	public boolean hasNextLine(){

		boolean result = true;
		try {
			//returns 0 if the file does not have more lines.
			if(dis.available() == 0)
				result = false;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	public void closeFile(){
		// dispose all the resources after using them.
		try {
			fis.close();
			bis.close();
			dis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
